package com.bizdk.generator.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bizdk.generator.common.page.PageResult;
import com.bizdk.generator.common.query.Query;
import com.bizdk.generator.core.DbType;
import com.bizdk.generator.core.GenDataSrc;
import com.bizdk.generator.entity.gen.Datasrc;
import com.bizdk.generator.mapper.DatasrcMapper;
import com.bizdk.generator.service.DatasrcService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;


/**
 * 数据源管理
 */
@Service
@AllArgsConstructor
@Slf4j
public class DatasrcServiceImpl extends ServiceImpl<DatasrcMapper, Datasrc> implements DatasrcService {
    
    @Autowired
    private final DataSource dataSource;
    
    @Override
    public PageResult<Datasrc> page(Query query) {
        IPage<Datasrc> page = baseMapper.selectPage(new Page<>(query.getPageNum(), query.getPageSize()), query.getWrapper());
        return new PageResult<>(page.getRecords(), page.getTotal());
    }
    
    @Override
    public List<Datasrc> getList() {
        return baseMapper.selectList(Wrappers.emptyWrapper());
    }
    
    @Override
    public String getDatabaseProductName(Long datasrcId) {
        if (datasrcId.intValue() == 0) {
            return DbType.MySQL.name();
        } else {
            return getById(datasrcId).getDbType();
        }
    }
    
    @Override
    public GenDataSrc get(Long datasrcId) {
        // 初始化配置信息
        GenDataSrc genDataSrc = null;
        if (0L == datasrcId) {
            try {
                genDataSrc = new GenDataSrc(dataSource.getConnection());
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        } else {
            genDataSrc = new GenDataSrc(this.getById(datasrcId));
        }
        
        return genDataSrc;
    }
    
    @Override
    public boolean save(Datasrc entity) {
        entity.setCreateTime(new Date());
        return super.save(entity);
    }
}